package com.xj.zhihudemo.ui.fragment;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.xj.zhihudemo.R;
import com.xj.zhihudemo.mode.ThemesInfo;
import com.xj.zhihudemo.retrofit.ApiClient;
import com.xj.zhihudemo.retrofit.ApiStore;
import com.xj.zhihudemo.ui.adapter.TestAdapter;
import com.xj.zhihudemo.ui.listener.RecyclerViewLoadMoreListener;
import com.xj.zhihudemo.utils.ToastUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static android.view.View.OVER_SCROLL_NEVER;

/**
 * Created by Xujing on 16/9/5.
 */
public class ThemesFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener, RecyclerViewLoadMoreListener.OnLoadMoreListener {
    private static final int PAGE_LIMIT = 10;
    private static ThemesFragment instance;
    private final String TAG = getClass().getSimpleName();
    @BindView(R.id.rv_themes)
    RecyclerView mRvThemes;
    SimpleDraweeView mIvThemesTop;
    TextView mTvThemesDescription;
    @BindView(R.id.srl_themes)
    SwipeRefreshLayout mSrlThemes;
    private int ThemesID;
    private Context mContext;
    //    private ThemesAdapter mAdapter;
    private TestAdapter mTestAdapter;
    private LinearLayoutManager mLayoutManager;
    private View mHeader;

    public static ThemesFragment getInstance() {
        if (instance == null) {
            instance = new ThemesFragment();
        }
        return instance;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = getArguments();
        ThemesID = bundle.getInt("ID");
        mContext = getActivity();
//        mAdapter = new ThemesAdapter(mContext);
        mTestAdapter = new TestAdapter(mContext);

    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View layout = inflater.inflate(R.layout.fragment_themes, container, false);
        ButterKnife.bind(this, layout);
        return layout;

    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {


        initView();

    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);

    }


    private void initHeader(RecyclerView rvThemes) {
        mHeader = LayoutInflater.from(mContext).inflate(R.layout.fragment_themes_header, rvThemes, false);
        mIvThemesTop = (SimpleDraweeView) mHeader.findViewById(R.id.iv_themes_top);
        mTvThemesDescription = (TextView) mHeader.findViewById(R.id.tv_themes_description);
    }

    private void initView() {

        mSrlThemes.setProgressBackgroundColorSchemeResource(android.R.color.white);
        mSrlThemes.setColorSchemeResources(
                android.R.color.holo_blue_light,
                android.R.color.holo_red_light,
                android.R.color.holo_green_light,
                android.R.color.holo_orange_light
        );
        mSrlThemes.setProgressViewOffset(false, 0, (int) TypedValue
                .applyDimension(TypedValue.COMPLEX_UNIT_DIP, 24, getResources()
                        .getDisplayMetrics()));
        mSrlThemes.setOnRefreshListener(this);
        mLayoutManager = new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false);
        mRvThemes.setLayoutManager(mLayoutManager);
        mRvThemes.setHasFixedSize(true);
        initHeader(mRvThemes);
        initData();
//        mRvThemes.setAdapter(mAdapter);
        mRvThemes.setOverScrollMode(OVER_SCROLL_NEVER);
        mRvThemes.setAdapter(mTestAdapter);
//        mAdapter.addHeader(mHeader);
        mTestAdapter.addHeader(mHeader);

//        mAdapter.setOnItemClickListener(new ThemesAdapter.ItemClick() {
//            @Override
//            public void onItemClick(View view, int position, ThemesInfo.StoriesEntity data, ArrayList<Integer> idList) {
////                ToastUtils.with(mContext).show("点击了新闻:" + position);
//                Log.d(TAG, "点击了新闻" + position);
//                Intent intent = new Intent();
//                Log.e(TAG, idList.size() + "");
//                intent.setClass(mContext, WebActivity.class);
//                intent.putExtra("index", position);
//                intent.putExtra("ids", idList);
//                startActivity(intent);
//            }
//
//            @Override
//            public void onItemLongClick(View view, int position, ThemesInfo.StoriesEntity data) {
//
//            }
//        });
        mRvThemes.setOnScrollListener(new RecyclerViewLoadMoreListener(mLayoutManager, this, PAGE_LIMIT));

    }


    private void initData() {


        ApiStore apiStore = ApiClient.retrofit().create(ApiStore.class);
        Call<ThemesInfo> themesInfoCall = apiStore.getTheme(ThemesID + "");
        themesInfoCall.enqueue(new Callback<ThemesInfo>() {
            @Override
            public void onResponse(Call<ThemesInfo> call, Response<ThemesInfo> response) {
                Log.d(TAG, "success");
                ThemesInfo themesInfo = response.body();
                if (themesInfo != null) {
                    Log.d(TAG, themesInfo.getImage());
                    mIvThemesTop.setImageURI(themesInfo.getImage());
                    mIvThemesTop.setColorFilter(R.color.translucent_status);
                    mTvThemesDescription.setText(themesInfo.getDescription());
//                    mAdapter.addDatas(themesInfo.getStories());
                    List<ThemesInfo.StoriesEntity> list = new ArrayList<ThemesInfo.StoriesEntity>();
                    for (int i = 0; i < 10; i++) {
                        list.add(themesInfo.getStories().get(i));
                    }
                    mTestAdapter.addDatas(list);


                }
            }

            @Override
            public void onFailure(Call<ThemesInfo> call, Throwable t) {

            }
        });
    }

    @Override
    public void onRefresh() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {

                mSrlThemes.setRefreshing(false);
                ToastUtils.with(mContext).show("刷新完毕");
                Log.d(TAG, "下拉刷新");
            }
        }, 3000);

    }

    @Override
    public void onLoadMore() {
        Log.d(TAG, "加载更多");
        if (mTestAdapter.canLoadMore()) {
            mTestAdapter.setLoading(true);
            mTestAdapter.notifyItemChanged(mTestAdapter.getItemCount() - 1);
//            ToastUtils.with(mContext).show("正在加载");
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    mTestAdapter.setLoading(false);
                    mTestAdapter.notifyItemChanged(mTestAdapter.getItemCount() - 1);
                }
            }, 2500);
        }

    }

    public void onLoadMoreTopicListFinish() {
        mTestAdapter.setLoading(false);
        mTestAdapter.notifyItemChanged(mTestAdapter.getItemCount() - 1);
    }
}

